// 文件名称：detail.js
// 完整保存路径：miniprogram/pages/feedback/detail/detail.js
// 功能说明：意见反馈详情页面逻辑控制
// 使用说明：处理反馈详情展示、管理员回复查看等功能

const { getToken } = require('../../../utils/auth.js');
const { buildMediaUrl } = require('../../../utils/media.js');

const app = getApp();

Page({
  data: {
    feedbackId: null,
    feedback: null,
    loading: true,
    refreshing: false
  },

  onLoad(options) {
    console.log('意见反馈详情页面加载');
    if (options.id) {
      this.setData({ feedbackId: parseInt(options.id) });
      this.loadFeedbackDetail();
    } else {
      wx.showToast({
        title: '缺少反馈ID',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
    }
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  /**
   * 加载反馈详情
   */
  async loadFeedbackDetail() {
    if (!this.data.feedbackId) return;
    
    try {
      this.setData({ loading: true });
      
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        });
        return;
      }
      
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/feedback/${this.data.feedbackId}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: resolve,
          fail: reject
        });
      });
      
      if (response.statusCode === 200 && (response.data.success || response.data.code === 0)) {
        const feedbackData = response.data.data;
        this.setData({
          feedback: feedbackData,
          loading: false,
          refreshing: false
        });
        
        wx.stopPullDownRefresh();
      } else {
        throw new Error(response.data.message || '获取反馈详情失败');
      }
      
    } catch (error) {
      console.error('加载反馈详情失败:', error);
      this.setData({
        loading: false,
        refreshing: false
      });
      
      wx.stopPullDownRefresh();
      wx.showToast({
        title: error.message || '加载反馈详情失败',
        icon: 'error'
      });
    }
  },

  /**
   * 刷新数据
   */
  async refreshData() {
    this.setData({
      refreshing: true
    });
    
    await this.loadFeedbackDetail();
  },

  /**
   * 预览图片
   */
  previewImage(e) {
    const index = e.currentTarget.dataset.index;
    const type = e.currentTarget.dataset.type; // 'feedback' or 'reply'
    
    let urls = [];
    if (type === 'feedback') {
      urls = this.data.feedback.images || [];
    } else if (type === 'reply') {
      urls = this.data.feedback.reply_images || [];
    }
    
    // 处理图片URL
    const processedUrls = urls.map(img => {
      // 如果是本地临时路径，直接返回
      if (img.startsWith('tmp/') || img.includes('tmp') || img.startsWith('wxfile://')) {
        return img;
      }
      // 如果是服务器相对路径，使用标准工具转换
      return buildMediaUrl(img);
    });
    
    if (processedUrls.length > 0) {
      wx.previewImage({
        current: processedUrls[index],
        urls: processedUrls
      });
    }
  },

  /**
   * 复制文本内容
   */
  copyText(e) {
    const text = e.currentTarget.dataset.text;
    if (text) {
      wx.setClipboardData({
        data: text,
        success: () => {
          wx.showToast({
            title: '已复制到剪贴板',
            icon: 'success',
            duration: 1500
          });
        }
      });
    }
  },

  /**
   * 获取反馈类型文本
   */
  getFeedbackTypeText(type) {
    const typeMap = {
      'bug': '功能故障',
      'suggestion': '功能建议',
      'other': '其他问题'
    };
    return typeMap[type] || '其他';
  },

  /**
   * 获取反馈状态文本
   */
  getFeedbackStatusText(status) {
    const statusMap = {
      'pending': '待处理',
      'processing': '处理中', 
      'resolved': '已解决',
      'closed': '已关闭'
    };
    return statusMap[status] || '未知状态';
  },

  /**
   * 格式化时间
   */
  formatTime(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  /**
   * 获取图片完整URL
   */
  getImageUrl(imagePath) {
    if (!imagePath) return '';
    
    // 如果是本地临时路径，直接返回
    if (imagePath.startsWith('tmp/') || imagePath.includes('tmp') || imagePath.startsWith('wxfile://')) {
      return imagePath;
    }
    
    // 使用标准工具处理服务器路径
    return buildMediaUrl(imagePath);
  }
});
